import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:iea/provider/base/base_resp.dart';
import 'package:iea/blocs/paidCauserDetail_blocs/detail_picBar_bloc.dart';
import 'package:iea/models/paidCauserDetail_models/detail_picBar_model.dart'; 
import 'package:iea/widgets/error.dart';
import 'package:iea/widgets/loading.dart';
import 'detail_subList.dart';

class PicBar extends StatefulWidget{
  @override 
  State<StatefulWidget> createState() => _PicBarState();
}

class _PicBarState extends State<PicBar>
  with AutomaticKeepAliveClientMixin<PicBar> {
  @override
  bool get wantKeepAlive => true;
  DetailPicBarBloc _bloc = new DetailPicBarBloc();
  ScrollController _controller = new ScrollController();
  DetailPicBarModel goodsDetail;
  int checkIndex = 0;
   _getGoodDetail() {
    Map<String, String> params = {'goodsId': '35'};
    _bloc.detailPicBar(params);
  }
  _unitConvert(val) {
    if (val > 9999) {
      final round = ((val / 100).round() / 100).toString();
      int index = round.indexOf('.');
      if (round.substring(index) == '.0') {
        return round.substring(0, index) + '万';
      } else {
        return double.parse(round).toStringAsFixed(2).toString() + '万';
      }
    } else {
      return val;
    }
  }
  @override
  void initState() {
    super.initState();
    _getGoodDetail();
  }
  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
  GlobalKey _sliverToBoxAdapterKey = new GlobalKey();
  GlobalKey _subListKey = new GlobalKey();
  @override
  Widget build(BuildContext context){
    super.build(context);
    ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(context);
    return StreamBuilder<BaseResp>(
      stream: _bloc.detailPicBarStream,
      builder: (context, AsyncSnapshot<BaseResp> snapshot) {
        if (snapshot.data != null && snapshot.hasData) {
          var response = snapshot.data;
          if (response.result == true && response.data != null) {
            goodsDetail = snapshot.data.data;
            return Scaffold(
              appBar: AppBar(
                iconTheme: IconThemeData(color: Colors.black),
                title: Text('详情页', style: TextStyle(color: Colors.black)),
                backgroundColor: Colors.white,
              ),
              backgroundColor: Colors.white,
              body: Stack(
                children: <Widget>[
                  CustomScrollView(
                    controller: _controller,
                    slivers: <Widget>[
                      SliverToBoxAdapter(
                        child: Column(
                          key: _sliverToBoxAdapterKey,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: <Widget>[
                            Container(
                              width: ScreenUtil().setWidth(375),
                              height: ScreenUtil().setHeight(208),
                              decoration: BoxDecoration(
                                image: DecorationImage(
                                  image: NetworkImage(goodsDetail.cover == null ? '' : goodsDetail.cover, scale: 1.0),
                                  fit: BoxFit.fill,
                                ),
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.all(15.0),
                              child: Text(goodsDetail.name,
                                style: TextStyle(fontSize: 24.0, color: Color.fromRGBO(25, 25, 25, 1), fontWeight: FontWeight.w600),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              ),
                            ),
                            Container(
                              padding: EdgeInsets.symmetric(horizontal: 15.0),
                              margin: EdgeInsets.only(bottom: 10.0),
                              child: Flex(
                                direction: Axis.horizontal,
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: <Widget>[
                                  Flexible(
                                    child: Row(
                                      children: <Widget>[
                                        Text(goodsDetail.discountPrice == null ? '￥' + goodsDetail.price.toString() : '￥' + goodsDetail.discountPrice.toString(),
                                          style: TextStyle(color: goodsDetail.discountPrice == null ? Color.fromRGBO(25, 25, 25, 0.8) : Color.fromRGBO(243, 110, 34, 1), fontSize: 27.0),
                                        ),
                                        Padding(padding: EdgeInsets.only(left: 15.0),),
                                        Text(goodsDetail.discountPrice == null ? '' :'￥' + goodsDetail.price.toString(),
                                          style: TextStyle(decoration: TextDecoration.lineThrough, color: Color.fromRGBO(153, 153, 153, 1), fontSize: 15.0),
                                        )
                                      ],
                                    ),
                                  ),
                                  Flexible(
                                    child: Text( goodsDetail.learnerCount == null ? '' : _unitConvert(goodsDetail.learnerCount) + '次学习',
                                      style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: 13.0),
                                    ),
                                  ),
                                ]
                              ),
                            ),
                          ]
                        )
                      ),
                      _tabBar(),
                      SubList(goodsDetail: goodsDetail, subListKey: _subListKey),
                    ],
                  ),
                  Positioned(
                    bottom: 0.0,
                    child: Container(
                      width: ScreenUtil().setWidth(375),
                      child: goodsDetail.bottomStatus == 1 ? bottomStatus_1() : (goodsDetail.bottomStatus == 3 ? bottomStatus_3() : (goodsDetail.bottomStatus == 4 ? bottomStatus_4() : null))
                    ),
                  )
                 ],
              )
            );
          } else {
            return ErrorPage();
          }
        } else {
          return LoadingPage();
        }
      }
    );
  }
  // 底部状态栏>购买
  Widget bottomStatus_1() {
    return Row(
      children: <Widget>[
        Container(
          width: ScreenUtil().setWidth(190),
          height: 52.0,
          color: Colors.white,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(goodsDetail.discountPrice == null ? '￥' + goodsDetail.price.toString() : '￥' + goodsDetail.discountPrice.toString(),
                style: TextStyle(fontSize: 27.0,color: goodsDetail.discountPrice == null ? Color.fromRGBO(25, 25, 25, 0.8) : Color.fromRGBO(243, 110, 34, 1)),
              ),
              Padding(padding: EdgeInsets.only(left: 12.0)),
              Text(goodsDetail.discountPrice == null ? '' :'￥' + goodsDetail.price.toString(),
                style: TextStyle(decoration: TextDecoration.lineThrough, fontSize: 14.0, color: Color.fromRGBO(153, 153, 153, 1)),
              )
            ],
          ),
        ),
        GestureDetector(
          onTap: () {
            print('咨询');
          },
          child: Container(
            width: ScreenUtil().setWidth(65),
            height: 52.0,
            decoration: BoxDecoration(color: Color.fromRGBO(255, 148, 86, 1)),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image(
                  image: AssetImage('assets/images/homepage/whiteProup.png'),
                  width: 25.0,
                  height: 21.0,
                  fit: BoxFit.contain,
                ),
                Text('咨询',
                  style: TextStyle(fontSize: 12.0, color: Colors.white, height: 1.1),
                )
              ],
            ),
          ),
        ),
        GestureDetector(
          onTap: () {
            print('购买咨询');
          },
          child: Container(
            width: ScreenUtil().setWidth(120),
            height: 52.0,
            decoration: BoxDecoration(color: Color.fromRGBO(243, 110, 34, 1)),
            child: Text('购买咨询',
              style: TextStyle(fontSize: 18.0, color: Colors.white, height: 1.7),
              textAlign: TextAlign.center,
            ),
          ),
        ),
      ],
    );
  }
  // 底部状态栏>已下架
  Widget bottomStatus_3() {
    return Opacity(
      opacity: 0.5,
      child: Container(
        height: 30.0,
        color: Colors.black,
        child: Text('产品已下架',
          style: TextStyle(fontSize: 13.0, color: Color.fromRGBO(255, 255, 255, 1), height: 1.5),
          textAlign: TextAlign.center,
        ),
      )
    );
  }
  // 底部状态栏>开始学习
  Widget bottomStatus_4() {
    return Row(
      children: <Widget>[
        GestureDetector(
          onTap: () {
            print('咨询');
          },
          child: Container(
            width: ScreenUtil().setWidth(85),
            height: 52.0,
            decoration: BoxDecoration(
              color: Colors.white
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Image(
                  image: AssetImage('assets/images/homepage/proup.png'),
                  width: 25.0,
                  height: 21.0,
                  fit: BoxFit.contain,
                ),
                Text('咨询',
                  style: TextStyle(fontSize: 12.0, color: Color.fromRGBO(51, 51, 51, 1), height: 1.1),
                )
              ],
            ),
          ),
        ),
        GestureDetector(
          onTap: () {
            print('开始学习');
          },
          child: Container(
            width: ScreenUtil().setWidth(290),
            height: 52.0,
            decoration: BoxDecoration(
              color: Color.fromRGBO(243, 110, 34, 1)
            ),
            child: Text('开始学习',
              style: TextStyle(fontSize: 18.0, color: Colors.white, height: 1.7),
              textAlign: TextAlign.center,
            ),
          ),
        )
      ],
    );
  }
  // tab切换
  Widget _tabBar() {
    return SliverPersistentHeader(
      pinned: true, //是否固定在顶部
      floating: true,
      delegate: _SliverAppBarDelegate(
          minHeight: 50, //收起的高度
          maxHeight: 50, //展开的最大高度
          child:  Container(
            width: ScreenUtil().setWidth(375),
            padding: EdgeInsets.only(top: 10.0),
            decoration: BoxDecoration(color: Colors.white),
            child: Row(
              children: <Widget>[
                Padding(padding: EdgeInsets.only(left: 15.0)),
                GestureDetector(
                  onTap: (){
                    setState(() {
                      checkIndex = 0;
                    });
                    RenderObject renderObject = _sliverToBoxAdapterKey.currentContext.findRenderObject();
                    // print(renderObject.semanticBounds);
                    // print(renderObject.paintBounds);
                    // print(_sliverToBoxAdapterKey.currentContext.size);
                    _controller.animateTo(renderObject.paintBounds.height,
                      duration: Duration(milliseconds: 300),
                      curve: Curves.ease
                    );
                  },
                  child: Column(
                    children: <Widget>[
                      Text('课程列表',
                        style: checkIndex == 0 ? TextStyle(color: Color.fromRGBO(51, 51, 51, 1), fontSize: 19.0, fontWeight: FontWeight.w600) : TextStyle(color: Color.fromRGBO(159, 159, 159, 1), fontSize: 15.0),
                      ),
                      Container(child: borderBottom(checkIndex == 0))
                    ],
                  ),
                ),
                Padding(padding: EdgeInsets.only(left: 37)),
                GestureDetector(
                  onTap: (){
                    setState(() {
                      checkIndex = 1;
                    });
                    RenderObject sliverToBoxAdapterKey = _sliverToBoxAdapterKey.currentContext.findRenderObject();
                    RenderObject subListKey = _subListKey.currentContext.findRenderObject();
                    double scrollTop = sliverToBoxAdapterKey.paintBounds.height + subListKey.paintBounds.height;
                    _controller.animateTo(scrollTop,
                      duration: Duration(milliseconds: 300),
                      curve: Curves.ease
                    );
                  },
                  child: Column(
                    children: <Widget>[
                      Text('课程介绍',
                        style: checkIndex == 1 ? TextStyle(color: Color.fromRGBO(51, 51, 51, 1), fontSize: 19.0, fontWeight: FontWeight.w600) : TextStyle(color: Color.fromRGBO(159, 159, 159, 1), fontSize: 15.0),
                      ),
                      Container(child: borderBottom(checkIndex == 1))
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
    );
  }
  // tab底部横线
  Widget borderBottom(bool i) {
    if (i) {
      return Container(
        width: 24.0,
        height: 4.0,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(2.0),
          color: Color.fromRGBO(243, 110, 34, 1),
        ),
      );
    } else {
      return Container();
    }
  }
}
// 实例化吸顶组件
class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => max(maxHeight, minHeight);

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}